package wy.hanyufang.cn.socket.handler;

import io.netty.channel.*;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import wy.hanyufang.cn.socket.SimpleChannelHandlerPool;
import wy.hanyufang.cn.utils.CacheUtil;

import java.text.MessageFormat;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 扫码登录逻辑处理
 * @author ： wyhanyufang@163.com
 * @time ： 9:31 PM 2021/9/22
 */
public class ScannerLoginSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private static final Logger logger = LoggerFactory.getLogger(ScannerLoginSocketHandler.class);
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ChannelId channelId = ctx.channel().id();
        logger.info("扫码登录处理handler，客户端开始建立连接...{}",channelId);
        SimpleChannelHandlerPool.channels.add(ctx.channel());

        TextWebSocketFrame frame = new TextWebSocketFrame(channelId.asLongText());

//        new Thread(()->sendMessage(ctx.channel(),"启动线程发送")).start();
//        sendMessage(ctx.channel(),"启动线程发送");
//        final CountDownLatch latch = new CountDownLatch(1);
        new Thread(()->{
            sendMessage(ctx.channel(), MessageFormat.format("channelId={0}",channelId));
            CacheUtil.set(channelId.asShortText(),ctx.channel());
//            latch.countDown();
        }).start();
//        latch.await(10,TimeUnit.SECONDS);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.info("接收客户端发送消息：{}",((TextWebSocketFrame)msg).text());
        sendMessage(ctx.channel(),"服务端给你发消息了");
//        super.channelRead(ctx, msg);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("扫码登录处理handler，客户端开始断开连接...{}",ctx.channel().id());
//        sendMessage(ctx.channel(),"hello world");
        SimpleChannelHandlerPool.channels.remove(ctx.channel());
    }

    public static void sendMessage(Channel channel, String message){
        logger.info("开始发送消息...{}",SimpleChannelHandlerPool.channels.size());
        SimpleChannelHandlerPool.channels.writeAndFlush(new TextWebSocketFrame(message)) ;
        try{
//            channelFuture.await();
        }
        catch (Exception ex){
            logger.error("webSocket消息发送异常",ex);
        }
    }
}
